import koa from 'koa'
import config from './config'
import path from 'path'
import session from 'koa-session'
import responseTime from './middleware/response-time'
import mail from "./middleware/mail";
import captcha from './middleware/captcha'
import { route } from './route'
import koa_body from 'koa-body'
import koa_static from 'koa-static'

class App {
    constructor(){
        this.app = new koa()
        this.middlewares = []
    }
    use(middle) {
        this.middlewares.push(middle)
    }
    start() {
        this.app.keys = config.appKey
        this.app.use(session(config.session, this.app))
        this.app.use(captcha)
        config.debug && this.app.use(responseTime)
        config.mail && this.app.use(mail())
        if(config.static_path) {
            for(let p of config.static_path) {
                console.log('dir====>', path.resolve(__dirname, `../${p}`))
                this.app.use(koa_static(path.resolve(__dirname, `../${p}`)))
            }
        }
        for(let middle of this.middlewares) {
            this.app.use(middle)
        }
        this.app.use(koa_body(config.upload))
        this.app.use(route(this.app, config.routes))
        this.app.listen(config.port || 3000)
        console.log(`服务器启动成功，监听：http://127.0.0.1:${config.port || 3000}}`)
    }
}
export default App
